package ru.nosport.matrixaria;

import java.io.*;

/**
 * Created by IntelliJ IDEA.
 * User: vfabr
 * Date: 16.02.2009
 * Time: 0:38:37
 */
public final class Fifo {
	
	static private String pipeName = "/home/vfabr/my_fifo";
	/**
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException {
		Fifo fifo = new Fifo();
		if (args[0].equalsIgnoreCase("send")) {
			fifo.send();
		} else {
			fifo.read();
		}
	}
	/**
	 * Send data to Unix Named Pipe.
	 * @throws IOException
	 */
	private void send() throws IOException {
		String data = "Hello world!";
		BufferedWriter pipeWriter = new BufferedWriter(
		 new OutputStreamWriter(new FileOutputStream(pipeName)));
		try {
			pipeWriter.write(data);
			pipeWriter.flush();
			// Must close IO for Named Pipe to fully receive data.
			pipeWriter.close();
			pipeWriter = new BufferedWriter(new OutputStreamWriter(
			 new FileOutputStream(pipeName)));
		} finally {
			if (pipeWriter!= null)
				pipeWriter.close();
		}
	}

	/**
	 * Read data from Unix Named Pipe.
	 *
	 */
	private void read() {
		String line = null;
		BufferedReader read = null;
		try {
			read = new BufferedReader(
				new FileReader(pipeName));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		line = null;
	    try {
			while (line == null) {
				line = read.readLine();
				if (line == null && read != null) {
					// Must close IO for Named Pipe to
					// fully receive data.
					read.close();
					read = new BufferedReader(
					 new FileReader(pipeName));
				} else {
				  System.out.println(line);
				  line = null;
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
			if (read != null)
				read.close();
			}catch(Exception ignore) {}
		}
	}
}
